package com.lanou3g.hw0418.q3;

import java.io.*;

/**
 * Created by dllo on 18/4/20.
 */
public class Main {
    public static void main(String[] args) {
        String rootPath = "/Users/dllo/Desktop/作业/Q2";
        String targetPath = "/Users/dllo/Desktop/作业/Q3";

        File file = new File(rootPath);
        for (File file1 : file.listFiles()) {
            if (file1.isFile() && file1.length() >= 1024 * 1024 * 1024) {
                split(file1, targetPath);
            }
        }
    }
    // file文件拆到targetath文件夹里

    /**
     * @param file       要拆的文件
     * @param targetPath 拆完放到Q3文件夹
     */
    public static void split(File file, String targetPath) {
        File targetDir = new File(targetPath, file.getName());
        // 创建文件夹
        targetDir.mkdir();

        // 读流
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        int index = 0; // 第几个文件

        try {
            bis = new BufferedInputStream(new FileInputStream(file));
            int pos = 0;
            byte[] buf = new byte[1024];
            File desFile = new File(targetDir, file.getName() + index);
            bos = new BufferedOutputStream(new FileOutputStream(desFile));
            long size = 0;

            while ((pos = bis.read(buf)) != -1) {
                // 写流
                bos.write(buf, 0, pos);
                // 每写400M bos就指向新的文件
                size += pos;
                if (size > 400 * 1024 * 1024) {
                    bos.close(); // 把原来的流关了
                    index++; // 下一个文件
                    size = 0;
                    // 指向新的文件夹
                    bos = new BufferedOutputStream(new FileOutputStream(new File(targetDir, file.getName() + index)));
                }
            }
            // while 外面
            bos.flush();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
